package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.AddressDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Address;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/***
 * 地址管理
 */

@Service(interfaceClass = AddressService.class)
@Transactional
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressDao addressDao;

    /***
     * 查询所有
     * @return
     */
    @Override
    public List<Address> findAll() {
        return addressDao.findAll();
    }

    /***
     * 删除地址
     * @param id
     */
    @Override
    public Result delete(Integer id) {
        //根据地址id 查询订单表中是否绑定
        Long count = addressDao.findOrderByAddressId(id);
        if (count > 0) {
            return new Result(false, "该地址被订单绑定无法删除");
        }
        addressDao.deleteById(id);
        return new Result(true, MessageConstant.DELETE_ADDRESS_SUCCESS);

    }

    /***
     * 新增地址
     * @param address
     */
    @Override
    public void add(Address address) {
        addressDao.add(address);
    }

    /***
     * 分页查询
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();//ThreadLocal
        PageHelper.startPage(currentPage,pageSize);//分页插件，会在执行sql之前将分页关键字追加到SQL后面

        Page<Address> page = addressDao.findByCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public String findAddressNameById(int id) {
        return addressDao.findAddressNameById(id);
    }
}
